package com.itic.mall.system.comeback.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpress;
import com.itic.mall.system.orderpayback.persistence.model.OrderPayback;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample.Criteria;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsVo;
import com.itic.mall.system.orderproducts.service.OrderProductsService;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.itic.mall.system.user.service.MallUserService;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;


@Controller
@RequestMapping(value="/system/comeback")
public class ComebackController
     extends BaseController {
    @Autowired
    private OrderProductsService orderProductsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MallUserService mallUserService;
    @Autowired
    private ProductService productService;
    @Autowired
   	protected OutCommonService outCommonService;
       
       //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
       private static final String MODEL_NAME_CHINA = "退换货管理";//中文名
       private static final String MODEL_NAME＿ENGLISH = "comeback";//英文名
       private static final String PAGE_COMMON_PATH = "/mall/system/comeback/comeback";//通用路径
       private static final String COMMON_URL = "/system/comeback/";//通用路径
       
       private static final String APP_KEY = "cf8b62b569aa3b3a56703ad9";
   	
   	   private static final String SECREAT = "63ade6815de8bd38752ec5ab";

       //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
      
       /*
        * 主页面
        */
       @RequestMapping(value="/init")
       public String init(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Main";
       }
       
       /*
        * 添加页面
        */
       @RequestMapping(value="/initAdd")
       public String initAdd(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Add";
       }
       
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initView")
       public String initView(String id , Model model){
       	if( StringHelper.isNotBlank(id) ) {
       		
       		OrderProducts temp  = orderProductsService.get(id);
       		
       		
       		List<OrderProductsVo> list = orderProductsService.listByOrderId(id);
       		
       		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
       		
       		model.addAttribute("viewEditProducts",iticJsonMapper.toJson(list));
       		
       		model.addAttribute("name_china", MODEL_NAME_CHINA);
           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
           	model.addAttribute("common_url", COMMON_URL);
       	}else {
               throw new ParameterErrorException();
           }
       	
       	return PAGE_COMMON_PATH+"View";
       }
       
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initNote")
       public String initNote(String id , Model model){
       	if( StringHelper.isNotBlank(id) ) {
       		
       		OrderProducts temp  = orderProductsService.get(id);
       		
       		
       		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
       		
       		
       		model.addAttribute("name_china", MODEL_NAME_CHINA);
           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
           	model.addAttribute("common_url", COMMON_URL);
       	}else {
               throw new ParameterErrorException();
           }
       	
       	return PAGE_COMMON_PATH+"Note";
       }
       
       /*
        * 跳转到退货物流页面
        */
       @RequestMapping(value="/initGiveback")
       public String initGiveBack( String id, Model model ){
    	   if( StringHelper.isNotBlank(id) ){
    		    OrderProducts temp  = orderProductsService.get(id);
          		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
          		model.addAttribute("orderProductsId",id);
          		model.addAttribute("name_china", MODEL_NAME_CHINA);
              	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
              	model.addAttribute("common_url", COMMON_URL);
    	   }else {
               throw new ParameterErrorException();
           }
       	
       	   return PAGE_COMMON_PATH+"Back";
       }
       
       
       //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
       
       
       /**
        * <p>Title:queryCondition </p>
        * <p>Description:封装查询条件 </p>
        * @param jzdw
        * @param jzdwExample
        * @return
        */
       private OrderProductsExample queryCondition(HttpServletRequest request,OrderProducts temp) {
       	
       	// 参数处理
    	   OrderProductsExample example = new OrderProductsExample();
           // 按创建时间倒序
           example.setOrderByClause("CREATE_TIME DESC");
           // 按排列号顺序
           example.setOrderByClause("REORDER ASC");
           
           Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE ).andStatusEqualTo("4");
         
           
           // 查询条件
           if ( null != temp ) {
        	   if( StringHelper.isNotBlank(temp.getBackStatus()) ){
        		   criteria.andBackStatusEqualTo(temp.getBackStatus());
        	   }
           }
           return example;
       }
       
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/list")
       @ResponseBody
       public Map<String, Object> list(OrderProducts temp, HttpServletRequest request){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           
           
           OrderProductsExample example = this.queryCondition(request,temp);
           // 封装分页参数
           example = this.handlePageQuery(request, example);
           
           
           // 获取信息总条数
           int total = orderProductsService.count(example);
           
           // 获取数据
           List<OrderProducts> list = orderProductsService.list(example);
           if( list.size() > 0 ){
        	   for( OrderProducts tmp: list ){
        		   Product product = productService.get(tmp.getProductId());
        		   if( null != product ){
        			   tmp.setProductId(product.getName());
        		   }
        		   
        		   MallUser mallUser = mallUserService.get(tmp.getUserId());
        		   if( null != mallUser ){
        			   tmp.setUserId(mallUser.getUserNickName());
        		   }
        		   
        	   }
           }
           
           // 数据返回处理
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;

       }
       
       
       

       /**
        * 退款，金额全部退还给用户余额中
        * 
        */
       @RequestMapping(value = "/payback")
       @ResponseBody
       public Map<String, String> payback(String id) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();
           if( StringHelper.isNotBlank(id) ){
               OrderProducts item = orderProductsService.get(id);
               //将订单项的退款状态设置成  退款状态
               item.setBackStatus("2");
               
               String totalMoney = item.getTotalMoney();
               
               //添加退款信息
               OrderPayback payback = new OrderPayback(); 
               payback.setId(IdGen.uuid());
               payback.setIsEffective(DBConst.TRUE);
               payback.setCreateTime( new Date() );
               payback.setUpdateTime( new Date() );
               payback.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper
                       .get(Constants.USER_ID) : "unknown");
               payback.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper
                    .get(Constants.USER_ORG) : "unknown");
               
               payback.setBackMoney(totalMoney);
               payback.setUserId(item.getUserId());
               payback.setOrderId(item.getOrderId());
               payback.setOrderProductId(item.getId());
               
               /*添加支出信息
               ExpendLog expendLog = new ExpendLog();
               expendLog.setId(IdGen.uuid());
               expendLog.setIsEffective(DBConst.TRUE);
               expendLog.setCreateTime( new Date() );
               expendLog.setUpdateTime( new Date() );
               expendLog.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper
                       .get(Constants.USER_ID) : "unknown");
               expendLog.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper
                    .get(Constants.USER_ORG) : "unknown");
               expendLog.setUserId(item.getUserId());
               expendLog.setMoney(totalMoney);
               expendLog.setNote("用户申请退款");
               //添加平台统计
               Statis lastStatis = statisService.getLastData();
               Statis statis = new Statis();
               statis.setId(IdGen.uuid());
               statis.setIsEffective(DBConst.TRUE);
               statis.setCreateTime( new Date() );
               statis.setUpdateTime( new Date() );
               statis.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper
                       .get(Constants.USER_ID) : "unknown");
               statis.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper
                    .get(Constants.USER_ORG) : "unknown");
               
               String statisMoney = "0";
               if( null != lastStatis ){
            	   statisMoney = lastStatis.getTotalMoney();
               }
               NumberStringHelper.subtractString(statisMoney, totalMoney);
               */
               
               //判断订单是否退换货，
               Order order = orderService.get(item.getOrderId());
               order.setStatus("4");
               
               result = orderProductsService.payBackNew(item,payback,order);
               pushMsg(item.getUserId(),"您的订单已退款，请到账户余额查看！");
           }
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       
       /**
        * 退货，添加退货物流信息
        * 
        */
       @RequestMapping(value = "/giveback")
       @ResponseBody
       public Map<String, String> giveback( OrderExpress express ) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();
           OrderProducts item = orderProductsService.get(express.getOrderProductsId());
           //将订单项的退款状态设置成  退货状态
           item.setBackStatus("3");
           //添加物流信息
           result = orderProductsService.giveback(item,express);
           pushMsg(item.getUserId(),"您申请换货已处理，请注意查收物流信息！");
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       /**
        * 退货，添加退货物流信息
        * 
        */
       @RequestMapping(value = "/note")
       @ResponseBody
       public Map<String, String> note( String id, String note ) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();
           OrderProducts item = orderProductsService.get(id);
           item.setNote(note);
           //添加物流信息
           result = orderProductsService.edit(item);
           
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       @RequestMapping(value="/pushMsg")
       @ResponseBody
       public void pushMsg( String userId ,String text ){
       	//推送消息到云店主
   		 JPushClient jpushClient = new JPushClient(SECREAT, APP_KEY, null, ClientConfig.getInstance());

   	    // For push, all you need do is to build PushPayload object.
   	    //PushPayload payload = buildPushObject_all_all_alert( text );
   	    
   		//PushPayload payload = buildPushObject_ios_audienceMore_messageWithExtras( userId,text );
   		PushPayload payload = buildPushObject_all_alias_alert(userId,text);
   	    try {
   	        PushResult tmpres = jpushClient.sendPush(payload);
   	       
   	        System.out.println(tmpres);
   	        //LOG.info("Got result - " + result);

   	    } catch (APIConnectionException e) {
   	        // Connection error, should retry later
   	        //LOG.error("Connection error, should retry later", e);
   	    	System.out.println(1);
   	    } catch (APIRequestException e) {
   	        // Should review the error, and fix the request
   	        //LOG.error("Should review the error, and fix the request", e);
   	        //LOG.info("HTTP Status: " + e.getStatus());
   	       // LOG.info("Error Code: " + e.getErrorCode());
   	        //LOG.info("Error Message: " + e.getErrorMessage());
   	    	System.out.println(2);
   	    }
   	    
       }

       public static PushPayload buildPushObject_all_all_alert( String text ) {
           return PushPayload.alertAll(text);
       }
       
       public static PushPayload buildPushObject_all_alias_alert( String userId, String text ) {
           return PushPayload.newBuilder()
                   .setPlatform(Platform.all())
                   .setAudience(Audience.alias(userId))
                   .setNotification(Notification.alert(text))
                   .build();
       }
       
       public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras( String userId,String text ) {
           return PushPayload.newBuilder()
                   .setPlatform(Platform.android_ios())
                   .setAudience(Audience.newBuilder()
                           .addAudienceTarget(AudienceTarget.tag(userId))
                           //.addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                           .build())
                   .setMessage(Message.newBuilder()
                           .setMsgContent(text)
                           //.addExtra("from", "JPush")
                           .build())
                   .build();
       }
}